package org.testframe;

import java.util.List;

/**
 * 一个流程
 * @author 丁常磊
 * @date 2023/11/17 9:47
 */

public class Flow {

    private final List<Action> actions;

    private final FlowContext flowContext;

    /**
     * 当前应该执行的步骤
     */
    private int currentStep = -1;

    private final Action finallyAction;

    private final Action errorAction;

    public Flow(List<Action> actions,Action finallyAction,Action errorAction,FlowContext flowContext) {
        this.actions = actions;
        this.finallyAction = finallyAction;
        this.errorAction = errorAction;
        this.flowContext = flowContext;
    }

    /**
     * 进行下一步
     */
    public void next() {
        if (isEnd()) {
            return;
        }

        currentStep++;

        Action action = actions.get(currentStep);

        try {
            boolean complete = action.play(flowContext);
            //如果没有完成, 退回到上一步. 等待下一个周期继续完成
            if (!complete) {
                currentStep--;
            }
        } catch (Throwable e) {
            //直接结束
            currentStep = actions.size();
            flowContext.setError(e);
            if (errorAction != null) {
                errorAction.play(flowContext);
            }
        }

    }

    public void runFinally() {
        if (this.finallyAction != null) {
            try {
                this.finallyAction.play(flowContext);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断流程是否终止了
     * @return
     */
    public boolean isEnd() {
        return currentStep + 1 >= actions.size();
    }

    public void bindBootStarter(FlowBootStarter flowBootStarter) {
        flowContext.setFlowBootStarter(flowBootStarter);
    }
}
